//
//  MainApplication.swift
//  MiU
//
//  Created by linhan on 15/11/16.
//  Copyright © 2015年 MiU. All rights reserved.
//

import Foundation
import UIKit

private let instance = SWMainApplication()

enum SWURLHost:String
{
    case Topic = "topic"
    case Brand = "brand"
    case Identify = "identify"
    case User = "user"
}

enum SWRemoteNotificationType:String
{
    case ShowUserDetail = "10"
    case ShowFeedDetail = "20"
    case ShowVideoDetail = "30"
    case ShowBrandDetail = "40"
    case ShowWebPage = "50"
}

class SWMainApplication: NSObject,PushManagerDelegate
{
    private var _setuped:Bool = false
    
    var launchOptions: [UIApplicationLaunchOptionsKey: Any]?
    var rootViewController:SWRootViewController?
    var mainViewController:UIViewController?
    
    class var sharedApplication:SWMainApplication
    {
        return instance
    }
    
    var navigationController: UINavigationController?
    {
        //return (rootViewController as? UITabBarController)?.selectedViewController as? UINavigationController
        return mainViewController as? UINavigationController
    }
    
    func launch(options:[UIApplicationLaunchOptionsKey: Any]?)
    {
        launchOptions = options
        
        //webview打开网页，进行缓存
        let memory:Int = 4 * 1024 * 1024
        let disk:Int = 20 * 1024 * 1024
        URLCache.shared.memoryCapacity = memory
        URLCache.shared.diskCapacity = disk
        
        WeiboHelper.redirectURI = "https://sns.bbyiya.com/sina2/callback"
        WeiboHelper.registerApp(appKey: SW.Config.WeiboAppKey)
        
        WeixinHelper.registerApp(appID: SW.Config.WechatAppID, appSecret: SW.Config.WechatAppSecret)
        
        QQSDKHelper.shared().registerApp(appID: SW.Config.QQAppID)
        
        
        SWAppearanceManager.sharedManager().setup()
        
        SWPushManager.shared().start(options)
        
        SWStatisticsManager.setup()
        
        //SWAccountManager.sharedManager().setup()
        
        SWAssetsManager.sharedManager().launch()
    }
    
    func mainViewControllerReady()
    {
        if !_setuped
        {
            _setuped = true
            setupPushManager()
            handleOpenViewControllerOnLaunch()
        }
    }
    
    private func handleOpenViewControllerOnLaunch()
    {
        let launchRemoteNotification = SWPushManager.shared().launchRemoteNotification
        SWPushManager.shared().launchRemoteNotification = nil
        if let launchRemoteNotification = launchRemoteNotification
        {
            handleRemoteNotification(launchRemoteNotification, launch: true)
            return
        }
        //需要的时候判断来源：UIApplicationLaunchOptionsSourceApplicationKey
        if let openURL = launchOptions?[UIApplicationLaunchOptionsKey.url] as? URL
        {
            handleOpenURL(openURL)
            return
        }
    }
    
    func handleOpenURL(_ url:URL) -> Bool
    {
        // miss://qa?debug=1
        // miss://webview?url=http://www.baidu.com
        // miss://topic?text=apple
        // miss://brand?name=apple
        // miss://user?uid=123
        
        let params = NetUtil.getQuery(url)
        var canHandleOpenURL:Bool = false
        if let host = url.host
        {
            if host == SWURLHost.Topic.rawValue
            {
                canHandleOpenURL = true
                //...
            }
        }
        return canHandleOpenURL
    }
    
    //推送管理器
    private func setupPushManager()
    {
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        SWPushManager.shared().addDelegate(self)
        
        let deviceToken:String = SWPushManager.shared().deviceToken
        if deviceToken != "" && !SWPushManager.shared().commitedDeviceToken
        {
            //commitDeviceToken(deviceToken)
        }
    }
    
    private func handleRemoteNotification(_ userInfo:[AnyHashable: Any], launch:Bool = false)
    {
        
    }
    
    
    //MARK ============================================================================================
    //==============================         PushManagerDelegate        ===============================
    //=================================================================================================
    
    //已经注册并获取设备TOKEN
    func didRegisterForRemoteNotifications(_ deviceToken:String)
    {
        let deviceToken:String = SWPushManager.shared().deviceToken
        if deviceToken != "" && !SWPushManager.shared().commitedDeviceToken
        {
            //commitDeviceToken(deviceToken)
        }
    }
    
    //收到远程通知
    func didReceiveRemoteNotification(_ userInfo:[NSObject : Any])
    {
        handleRemoteNotification(userInfo)
        //Alert.show("", message: "接收到推送通知 \(userInfo.description)", buttons: ["确定"])
        //trace("接收到推送通知\(userInfo)")
    }
    
    
    
    
    
    
    
}
